//
//  NMNMRetakeViewController.m
//  HNJYB
//
//  Created by Mag1cPanda on 2017/3/23.
//  Copyright © 2017年 Mag1cPanda. All rights reserved.
//

#import "NMNMRetakeViewController.h"
#import "AccidentHeader.h"
#import "CaseAuditViewController.h"
#import "CollectionFooter.h"
#import "CollectionHeader.h"
#import "DJCameraManager.h"
#import "DJCameraViewController.h"
#import "JCAlertView.h"
#import "SRBlockButton.h"
#import "TakePhotoCell.h"
#import "XZQXViewController.h"

@interface NMNMRetakeViewController ()
<DJCameraViewControllerDelegate,
UICollectionViewDataSource,
UICollectionViewDelegate,
UICollectionViewDelegateFlowLayout,
UIImagePickerControllerDelegate,
UINavigationControllerDelegate,
AVAudioPlayerDelegate,
UIAlertViewDelegate>
{
    UICollectionView* collection;
    NSMutableDictionary* cellDic;
    AccidentHeader* header;
    NSMutableArray* iconArr;
    NSMutableArray* titleArr;
    NSMutableArray* tipsArr;
    JCAlertView* jcAlert;
    
    NSMutableDictionary* uploadBean;
    NSMutableDictionary* photoDic;
    
    BOOL isSuccess;
    
    NSString *nmjfzmIMGStr;
    NSString *nmjffmIMGStr;
    NSString *nmyfzmIMGStr;
    NSString *nmyffmIMGStr;
    
}

@end

static NSString* const headerId = @"headerId";
static NSString* const footerId = @"footerId";

@implementation NMNMRetakeViewController

#pragma mark - LifeCycle

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    
    self.title = @"上传事故照片";
    
    photoDic = [NSMutableDictionary dictionary];
    uploadBean = [NSMutableDictionary dictionary];
    cellDic = [NSMutableDictionary dictionary];
    [self initUploadBean:uploadBean];
    
    iconArr = @[ @"nmnmicon1",
                 @"nmnmicon2",
                 @"nmnmicon3",
                 @"nmnmicon4",
                 @"sfzfm",
                 @"sfzzm",
                 @"sfzfm",
                 @"sfzzm"].mutableCopy;
    
    titleArr = @[ @"车头前方",
                  @"车尾后方",
                  @"擦碰点",
                  @"事故侧方全景",
                  @"甲方身份证正面",
                  @"甲方身份证反面",
                  @"乙方身份证正面",
                  @"乙方身份证反面"].mutableCopy;
    
    tipsArr = @[ @"nmnmtips1",
                 @"nmnmtips2",
                 @"nmnmtips3",
                 @"nmnmtips4",
                 @"sfzfmtips",
                 @"sfzzmtips",
                 @"sfzfmtips",
                 @"sfzzmtips"].mutableCopy;
    
    UICollectionViewFlowLayout* layout = [[UICollectionViewFlowLayout alloc] init];
    layout.scrollDirection = UICollectionViewScrollDirectionVertical;
    layout.minimumLineSpacing = 10;
    [layout setHeaderReferenceSize:CGSizeMake(ScreenWidth, 100)];
    [layout setFooterReferenceSize:CGSizeMake(ScreenWidth, 100)];
    
    collection = [[UICollectionView alloc] initWithFrame:CGRectMake(0, 0, ScreenWidth, ScreenHeight - 64) collectionViewLayout:layout];
    collection.backgroundColor = [UIColor clearColor];
    collection.delegate = self;
    collection.dataSource = self;
    //    collection.bounces = NO;
    [self.view addSubview:collection];
    
    //注册Cell Id
    for (NSInteger i = 0; i < 10; i++) {
        NSString* cellId = [NSString stringWithFormat:@"TakePhotoCell%zi", i];
        [collection registerNib:[UINib nibWithNibName:@"TakePhotoCell" bundle:nil] forCellWithReuseIdentifier:cellId];
    }
    
    //注册Header & Footer Id
    [collection registerClass:[CollectionHeader class] forSupplementaryViewOfKind:UICollectionElementKindSectionHeader withReuseIdentifier:headerId];
    [collection registerClass:[CollectionFooter class] forSupplementaryViewOfKind:UICollectionElementKindSectionFooter withReuseIdentifier:footerId];
    
    [self loadSuccessedImage];
    
}

#pragma mark - 加载合格照片
-(void)loadSuccessedImage
{
    if (_isHistoryPush) {
        NSMutableDictionary *bean = [NSMutableDictionary dictionary];
        [bean setValue:GlobleInstance.userflag forKey:@"username"];
        [bean setValue:GlobleInstance.token forKey:@"token"];
        [bean setValue:GlobleInstance.appcaseno forKey:@"appcaseno"];
        [bean setValue:@"1" forKey:@"imgtype"];
        
        [LSHttpManager requestUrl:HNServiceURL serviceName:@"jjappGetSucPassImgUrl" parameters:bean complete:^(id result, ResultType resultType) {
            
            if (result) {
                NSLog(@"双车审核未通过重拍 ~ %@",[Util objectToJson:result]);
            }
            
            if ([result[@"restate"] isEqualToString:@"1"]) {
                
                _qualifiedArr = result[@"data"][@"passlist"];
                _unQualifiedArr = result[@"data"][@"notpasslist"];
                [collection reloadData];
            }
            
        }];
    }
    
}

#pragma mark - 初始化上传Bean
- (void)initUploadBean:(NSMutableDictionary*)bean
{
    NSString* imagelat = [NSString stringWithFormat:@"%f", GlobleInstance.imagelat];
    NSString* imagelon = [NSString stringWithFormat:@"%f", GlobleInstance.imagelon];
    NSString* imageaddress = [NSString stringWithFormat:@"%@", GlobleInstance.imageaddress];
    NSString* appcaseno = [NSString stringWithFormat:@"%@", GlobleInstance.appcaseno];
    
    [bean setValue:appcaseno forKey:@"appcaseno"];
    [bean setValue:imagelat forKey:@"imagelat"];
    [bean setValue:imagelon forKey:@"imagelon"];
    [bean setValue:imageaddress forKey:@"imageaddress"];
    [bean setValue:@"1" forKey:@"shoottype"];
    //实例化一个NSDateFormatter对象
    NSDateFormatter* dateFormatter = [[NSDateFormatter alloc] init];
    //设定时间格式,这里可以设置成自己需要的格式
    [dateFormatter setDateFormat:@"yyyy-MM-dd HH:mm:ss"];
    //用[NSDate date]可以获取系统当前时间
    NSString* currentDateStr = [dateFormatter stringFromDate:[NSDate date]];
    //输出格式为：2010-10-27 10:22:13
    NSLog(@"%@", currentDateStr);
    
    NSString* username = [NSString stringWithFormat:@"%@", GlobleInstance.userflag];
    NSString* token = [NSString stringWithFormat:@"%@", GlobleInstance.token];
    NSString* areaid = [NSString stringWithFormat:@"%@", GlobleInstance.areaid];
    
    [bean setValue:currentDateStr forKey:@"imagedate"];
    [bean setValue:username forKey:@"username"];
    [bean setValue:token forKey:@"token"];
    [bean setValue:areaid forKey:@"areaid"];
}

#pragma mark - 拍照
- (void)takePhotoWithIndex:(NSIndexPath*)indexPath
{
    DJCameraViewController* cameraVC = [DJCameraViewController new];
    if (indexPath.item < 8) {
        cameraVC.guideImageName = tipsArr[indexPath.item];
    }
    else {
        cameraVC.guideImageName = @"car_one_zhuang";
    }
    cameraVC.titleStr1 = titleArr[indexPath.item];
    cameraVC.isLandscape = YES;
    cameraVC.isShowWarnImage = YES;
    cameraVC.delegate = self;
    cameraVC.index = indexPath.item;
    [self presentViewController:cameraVC animated:YES completion:nil];
}

#pragma mark - 相机代理
- (void)cameraViewController:(DJCameraViewController*)cameraVC ToObtainCameraPhotos:(UIImage*)image
{
    [self uploadImageWith:image index:cameraVC.index];
}

#pragma mark - 上传照片
- (void)uploadImageWith:(UIImage *)image index:(NSInteger)index
{
    NSString* imageWidth = [NSString stringWithFormat:@"%f", image.size.width];
    NSString* imageHeight = [NSString stringWithFormat:@"%f", image.size.height];
    NSData* imageData = UIImageJPEGRepresentation(image, 0.25);
    NSString* imageBig = [NSString stringWithFormat:@"%zi", imageData.length / 1024];
    
    NSString* imageStr = [Util imageToString:image];
    
    NSNumber *type;
    
    if (index == 0 || index == 1 || index == 2 || index == 3)
    {
        type = [NSNumber numberWithInteger:index];
    }
    
    //非机动车甲方身份证反面
    if (index == 4) {
        type = @16;
        nmjfzmIMGStr = imageStr;
    }
    //非机动车甲方身份证反面
    if (index == 5) {
        type = @17;
        nmjffmIMGStr = imageStr;
    }
    //非机动车乙方身份证正面
    if (index == 6) {
        type = @18;
        nmyfzmIMGStr = imageStr;
    }
    //非机动车乙方身份证反面
    if (index == 7) {
        type = @19;
        nmyffmIMGStr = imageStr;
    }
    
    NSString* token = [NSString stringWithFormat:@"%@", GlobleInstance.token];
    [uploadBean setValue:token forKey:@"token"];
    [uploadBean setValue:imageStr forKey:@"imageurl"];
    [uploadBean setValue:imageBig forKey:@"imagebig"];
    [uploadBean setValue:imageWidth forKey:@"imagewide"];
    [uploadBean setValue:imageHeight forKey:@"imageheigth"];
    [uploadBean setValue:type forKey:@"imagetype"];
    
    NSLog(@"imagetype -> %@", type);
    
    [LSHttpManager requestUrl:HNServiceURL serviceName:@"jjappzdsubmitcaseimage" parameters:uploadBean complete:^(id result, ResultType resultType) {
        
        if (result) {
            NSLog(@"%zi -> %@", index, [Util objectToJson:result]);
        }
        
        if ([result[@"restate"] isEqualToString:@"1"]) {
            
            //上传成功将照片显示在Cell上
            NSIndexPath *indexPath = [NSIndexPath indexPathForItem:index inSection:0];
            TakePhotoCell *cell = (TakePhotoCell *)[collection cellForItemAtIndexPath:indexPath];
            cell.icon.image = image;
            NSString *indexStr = [NSString stringWithFormat:@"%zi", index];
            [photoDic setValue:@"1" forKey:indexStr];
            
            [self ocrUploadedPhotos];
        }
        
        //非交警执勤时间的处理
        else if ([result[@"restate"] isEqualToString:@"-13"]) {
            
            UIAlertController *alertController = [UIAlertController alertControllerWithTitle:@"温馨提示"message:result[@"redes"] preferredStyle:UIAlertControllerStyleAlert];
            
            UIAlertAction *okAction = [UIAlertAction actionWithTitle:@"确定"style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
                
                [self.navigationController popToRootViewControllerAnimated:YES];
                
            }];
            
            
            [alertController addAction:okAction];
            
            [self presentViewController:alertController animated:YES completion:nil];
        }
        
        else {
            SHOWALERT(result[@"redes"]);
        }
    }];
}

#pragma mark - 上传按钮点击事件
- (void)uploadBtnClicked
{
    //再次点击按钮，如果已经上传成功，则直接弹出对话框
    if (isSuccess) {
        [self showAlertView];
        return;
    }
    
    //使用循环查找是否拍摄了所有必拍照片
    for (NSInteger i = 0; i < _unQualifiedArr.count; i++)
    {
        NSDictionary *dic = _unQualifiedArr[i];
        NSNumber *imagetype = dic[@"imagetype"];
        NSString *tmpStr = [NSString stringWithFormat:@"%@", imagetype];
        
        UIImage *image = photoDic[tmpStr];
        
        if (!image)
        {
            if (_isHistoryPush) {
                SHOWALERT(@"请您拍摄完照片后进行下一步");
                return;
            }
            
            else {
                NSString *msg = [NSString stringWithFormat:@"%@", dic[@"value"]];
                SHOWALERT(msg);
                return; //终止循环
            }
            
        }
    }
    
    if (photoDic.allKeys.count == _unQualifiedArr.count) {
        
        isSuccess = YES;
        [self showAlertView];
        
        //照片上传完成
        NSMutableDictionary* bean = [NSMutableDictionary dictionary];
        [bean setValue:GlobleInstance.appcaseno forKey:@"appcaseno"];
        [bean setValue:@"data" forKey:@"data"];
        [bean setValue:@"issingle" forKey:@"issingle"];
        
        [LSHttpManager requestUrl:HNServiceURL serviceName:@"jjappUploadImgIsover" parameters:bean complete:^(id result, ResultType resultType) {
            
            if ([result[@"restate"] isEqualToString:@"1"]) {
                NSLog(@"jjappUploadImgIsover -> %@", [Util objectToJson:result]);
            }
            
        }];
    }
}

#pragma mark - 识别已上传的照片
-(void)ocrUploadedPhotos
{
    NSMutableDictionary *ocrBean = [NSMutableDictionary dictionary];
    [ocrBean setValue:GlobleInstance.userflag forKey:@"userflag"];
    [ocrBean setValue:GlobleInstance.token forKey:@"token"];
    [ocrBean setValue:GlobleInstance.appcaseno forKey:@"appcaseno"];
    
//    MBProgressHUD *ocrHud = [MBProgressHUD showHUDAddedTo:self.view animated:YES];
//    ocrHud.label.text = @"正在识别中...";
    
    [LSHttpManager requestUrl:HNServiceURL serviceName:@"jjappOCR" parameters:ocrBean complete:^(id result, ResultType resultType) {
        
        NSLog(@"jjappOCR ~ %@",result);
        
    }];
    
}

#pragma mark - 显示上传完成提示框
- (void)showAlertView
{
    UIView* customView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, ScreenWidth - 60, 200)];
    customView.backgroundColor = [UIColor whiteColor];
    customView.layer.cornerRadius = 5;
    customView.clipsToBounds = YES;
    
    UIImageView* icon = [[UIImageView alloc] initWithFrame:CGRectMake(customView.width / 2 - 30, 20, 60, 60)];
    icon.image = [UIImage imageNamed:@"IP030"];
    [customView addSubview:icon];
    
    UILabel* lab = [[UILabel alloc] initWithFrame:CGRectMake(0, icon.maxY + 20, customView.width, 20)];
    lab.font = HNFont(14);
    lab.text = @"事故照片上传成功，请进入下一步";
    lab.textColor = [UIColor darkGrayColor];
    lab.textAlignment = NSTextAlignmentCenter;
    [customView addSubview:lab];
    
    UIView* horizontalLine = [[UIView alloc] initWithFrame:CGRectMake(0, lab.maxY + 20, customView.width, 1)];
    horizontalLine.backgroundColor = RGB(235, 235, 235);
    [customView addSubview:horizontalLine];
    UIView* verticalLine = [[UIView alloc] initWithFrame:CGRectMake(customView.width / 2, lab.maxY + 20, 1, 60)];
    verticalLine.backgroundColor = RGB(235, 235, 235);
    [customView addSubview:verticalLine];
    
    UIColor* color = [UIColor blackColor];
    
    SRBlockButton* confirmBtn = [[SRBlockButton alloc] initWithFrame:CGRectMake(0, lab.maxY + 21, customView.width / 2, 60) title:@"确认" titleColor:color handleBlock:^(SRBlockButton* btn) {
        
        [jcAlert dismissWithCompletion:nil];
        
        //协警
        if (GlobleInstance.userType == AuxiliaryPolice) {
            CaseAuditViewController* vc = [CaseAuditViewController new];
            vc.photoCount = photoDic.allKeys.count;
            [self.navigationController pushViewController:vc animated:YES];
        }
        
        //交警
        else {
            XZQXViewController* vc = [XZQXViewController new];
            [self.navigationController pushViewController:vc animated:YES];
        }
        
    }];
    [customView addSubview:confirmBtn];
    
    SRBlockButton* cancelBtn = [[SRBlockButton alloc] initWithFrame:CGRectMake(confirmBtn.maxX + 1, lab.maxY + 21, customView.width / 2, 60) title:@"返回" titleColor:color handleBlock:^(SRBlockButton* btn) {
        
        [jcAlert dismissWithCompletion:^{
            
        }];
        
    }];
    [customView addSubview:cancelBtn];
    
    jcAlert = [[JCAlertView alloc] initWithCustomView:customView dismissWhenTouchedBackground:YES];
    [jcAlert show];
}

#pragma mark - UICollectionViewDataSource

- (NSInteger)collectionView:(UICollectionView*)collectionView numberOfItemsInSection:(NSInteger)section
{
    return iconArr.count;
}

- (UICollectionViewCell*)collectionView:(UICollectionView*)collectionView cellForItemAtIndexPath:(NSIndexPath*)indexPath
{
    NSString* cellId = [NSString stringWithFormat:@"TakePhotoCell%zi", indexPath.item];
    TakePhotoCell* cell = [collectionView dequeueReusableCellWithReuseIdentifier:cellId forIndexPath:indexPath];
    UIImage* image = cell.icon.image;
    
    if (!image) {
        cell.titleLab.text = titleArr[indexPath.row];
        cell.icon.image = [UIImage imageNamed:iconArr[indexPath.row]];
    }
    
    for (NSDictionary *dic in _qualifiedArr)
    {
        if ([dic[@"imagetype"] isEqualToString:@"0"] && indexPath.row == 0)
        {
            [cell.icon sd_setImageWithURL:[NSURL URLWithString:dic[@"imageurl"]] placeholderImage:[UIImage imageNamed:iconArr[indexPath.row]]];
        }
        
        if ([dic[@"imagetype"] isEqualToString:@"1"] && indexPath.row == 1)
        {
            [cell.icon sd_setImageWithURL:[NSURL URLWithString:dic[@"imageurl"]] placeholderImage:[UIImage imageNamed:iconArr[indexPath.row]]];
        }
        
        if ([dic[@"imagetype"] isEqualToString:@"2"] && indexPath.row == 2)
        {
            [cell.icon sd_setImageWithURL:[NSURL URLWithString:dic[@"imageurl"]] placeholderImage:[UIImage imageNamed:iconArr[indexPath.row]]];
        }
        
        if ([dic[@"imagetype"] isEqualToString:@"3"] && indexPath.row == 3)
        {
            [cell.icon sd_setImageWithURL:[NSURL URLWithString:dic[@"imageurl"]] placeholderImage:[UIImage imageNamed:iconArr[indexPath.row]]];
        }
        
        if ([dic[@"imagetype"] isEqualToString:@"16"] && indexPath.row == 4)
        {
            [cell.icon sd_setImageWithURL:[NSURL URLWithString:dic[@"imageurl"]] placeholderImage:[UIImage imageNamed:iconArr[indexPath.row]]];
        }
        
        if ([dic[@"imagetype"] isEqualToString:@"17"] && indexPath.row == 5)
        {
            [cell.icon sd_setImageWithURL:[NSURL URLWithString:dic[@"imageurl"]] placeholderImage:[UIImage imageNamed:iconArr[indexPath.row]]];
        }
        
        if ([dic[@"imagetype"] isEqualToString:@"18"] && indexPath.row == 6)
        {
            [cell.icon sd_setImageWithURL:[NSURL URLWithString:dic[@"imageurl"]] placeholderImage:[UIImage imageNamed:iconArr[indexPath.row]]];
        }
        
        if ([dic[@"imagetype"] isEqualToString:@"19"] && indexPath.row == 7)
        {
            [cell.icon sd_setImageWithURL:[NSURL URLWithString:dic[@"imageurl"]] placeholderImage:[UIImage imageNamed:iconArr[indexPath.row]]];
        }
    }
    
    return cell;
}

// 和UITableView类似，UICollectionView也可设置段头段尾
- (UICollectionReusableView*)collectionView:(UICollectionView*)collectionView viewForSupplementaryElementOfKind:(NSString*)kind atIndexPath:(NSIndexPath*)indexPath
{
    if ([kind isEqualToString:UICollectionElementKindSectionHeader]) {
        CollectionHeader* headerView = [collectionView dequeueReusableSupplementaryViewOfKind:kind withReuseIdentifier:headerId forIndexPath:indexPath];
        
        return headerView;
    }
    else if ([kind isEqualToString:UICollectionElementKindSectionFooter]) {
        CollectionFooter* footerView = [collectionView dequeueReusableSupplementaryViewOfKind:kind withReuseIdentifier:footerId forIndexPath:indexPath];
        [footerView.btn addTarget:self action:@selector(uploadBtnClicked) forControlEvents:1 << 6];
        return footerView;
    }
    
    return nil;
}

#pragma mark - UICollectionViewDelegate
- (void)collectionView:(UICollectionView*)collectionView didSelectItemAtIndexPath:(NSIndexPath*)indexPath
{
    NSLog(@"item ~ %zi", indexPath.item);
    
    //拍摄照片
    [self takePhotoWithIndex:indexPath];
    
}

#pragma mark - UICollectionViewDelegateFlowLayout
- (CGSize)collectionView:(UICollectionView*)collectionView layout:(UICollectionViewLayout*)collectionViewLayout sizeForItemAtIndexPath:(NSIndexPath*)indexPath
{
    CGFloat width = (ScreenWidth - 30) / 2;
    return (CGSize){ width, width / 1.64 + 20 };
}

- (UIEdgeInsets)collectionView:(UICollectionView*)collectionView layout:(UICollectionViewLayout*)collectionViewLayout insetForSectionAtIndex:(NSInteger)section
{
    return UIEdgeInsetsMake(10, 10, 10, 10);
}

- (CGSize)collectionView:(UICollectionView*)collectionView layout:(UICollectionViewLayout*)collectionViewLayout referenceSizeForHeaderInSection:(NSInteger)section
{
    return (CGSize){ ScreenWidth, 100 };
}

- (CGSize)collectionView:(UICollectionView*)collectionView layout:(UICollectionViewLayout*)collectionViewLayout referenceSizeForFooterInSection:(NSInteger)section
{
    return (CGSize){ ScreenWidth, 100 };
}


@end
